package cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

public class aba {
    public static void main(String[] args) {
        //integer使用了对象缓存机制，超出了-128~127重新创建对象
        //AtomicStampedReferencer如果泛型是一个包装类，注意对象引用问题
        //AtomicStampedReference<Object> objectAtomicStampedReference = new AtomicStampedReference<>(2020,2021);
        //每次被动过版本号加一
        //正常业务操作这里比较的是一个个对象
        AtomicStampedReference<Integer> objectAtomicStampedReference = new AtomicStampedReference<>(1,1);

        //乐观锁的原理相同
        new Thread(()->{
            int stamp = objectAtomicStampedReference.getStamp();//获得版本号
            System.out.println("a1->"+stamp);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            objectAtomicStampedReference.compareAndSet(1,2,objectAtomicStampedReference.getStamp(), objectAtomicStampedReference.getStamp()+1);
            System.out.println("a2->"+objectAtomicStampedReference.getStamp());
            objectAtomicStampedReference.compareAndSet(2,1,objectAtomicStampedReference.getStamp(), objectAtomicStampedReference.getStamp()+1);
            System.out.println("a3->"+objectAtomicStampedReference.getStamp());
        },"a").start();
        new Thread(()->{
            int stamp = objectAtomicStampedReference.getStamp();//获得版本号
            System.out.println("b1->"+stamp);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            objectAtomicStampedReference.compareAndSet(2,6,stamp,stamp+1);
            System.out.println("b2->"+objectAtomicStampedReference.getStamp());

        },"b").start();
    }
}
